<?php
# Application
define('APP', dirname(__file__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR);

# Framework
require APP.'fw'.DIRECTORY_SEPARATOR.'init.php';

# Connection
fw::connect();

# Data
$place = (int) $_GET['place'];
$range = $_GET['range'];
$order = $_GET['order'];
$index = (int) $_GET['index'];

if($place && !db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE `id`='.$place))) $place = 0;

$query = ' FROM `'.DB_PREFIX.'Image`';

# Range
if($order == 'null')
{
	$query .= ' WHERE `upload_id`="'.db::escape($range).'"';
} else
{
	$query .= ' WHERE `private`=0';
	
	if($place) $query .= ' AND `User_id`='.$place;

	switch($range)
	{
		case 'month':
			$query .= ' AND `date` > NOW() - INTERVAL 1 MONTH';
			break;
		case 'week':
			$query .= ' AND `date` > NOW() - INTERVAL 1 WEEK';
			break;
		case 'today':
			$query.= ' AND `date` > NOW() - INTERVAL 1 DAY';
			break;
	}
}

$gallery = db::fetch(db::query('SELECT COUNT(*) AS `total`'.$query), 'row');
$total = $gallery[0];

switch($order)
{
	case 'null':
		$query .= ' ORDER BY `id` ASC';
		break;
	case 'new':
		$query .= ' ORDER BY `date` DESC';
		break;
	case 'popular':
		$query .= ' ORDER BY `views` DESC';
		break;
}

# Get index
if($index < 0)
{
	$index += $total;
} elseif($index >= $total)
{
	$index -= $total;
}

echo $index."\t".$total;

$query = 'SELECT `id`, `extension`, `title`'.$query.' LIMIT ';

function output($index, $limit)
{
	global $query;
	
	$gallery = db::query($query.$index.','.$limit);
	
	while($image = db::fetch($gallery, 'row'))
	{
		$in = $image[0];
		
		$index = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
		
		$base = strlen($index);
		
		$out = '';
		
		for($t=floor(log($in, $base)); $t>=0; $t--)
		{
			$bcp = bcpow($base, $t);
			$a   = floor($in /$bcp) % $base;
			$out = $out . substr($index, $a, 1);
			$in  = $in - ($a * $bcp);
		}
		
		echo "\n".$image[0]."\t".strrev($out)."\t".$image[1]."\t".$image[2];
	}
}

output($index, 5);

if($index + 5 >= $total)
{
	output(0, $index + 5 - $total);
}